#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import os
import sys
import web
import json

import Umpweb
from Umpweb.base import session, _
from Umpweb.common.utils import local_exec
from Umpweb.common import utils, config
from Umpweb.db import api as db_api
from Umpweb.base import session, _, render_jinja
from Umpweb.common.utils import login_required

render = render_jinja('static/templates/opconfig', encoding='utf-8', )


class SysconfigForUMPList:
    @login_required
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.opconfig_list()


class SysconfigForUMPCreate:
    @login_required

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = {
            'name':x.get('name').strip(),
            'value_setting':x.get('value_setting').strip(),
            'description':x.get('description').strip(),
        }
        if x.get('category'):
            values['category'] = x.get('category')

        body = {"SysconfigForUMPCreate": {'params': values}}
        return utils.web_return(body)


class GridSysconfigForUMP:
    @login_required
    def GET(self):
        web_input = web.input()
        page, total, records, rows = \
            utils.grid_rows_query(db_api.sysconfig_for_ump_table, web_input, filters={})

        cells = ['id', 'name', 'category', 'description', 'value_setting']
        rows_json = utils.grid_json(page, total, records, rows, 'id', cells)

        web.header("Content-Type", "application/json")
        return rows_json


class SysconfigForUMPUpdate:
    @login_required
    def GET(self):
        x = web.input()

        config_id = x.get('config_id')
        sysconfig_for_ump = db_api.sysconfig_for_ump_get(config_id)
        return render.opconfig_update(sysconfig_for_ump=sysconfig_for_ump)

    @login_required
    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()

        values = {
            'id': x.get('id').strip(),
            'value': x.value.strip(),
        }
        body = {"SysconfigForUMPUpdate": {'params': values}}
        return utils.web_return(body)
